<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <SmForm
      class="-mb-15px"
      ref="formRef"
      isCol
      label-width="150px"
      v-model="formData"
      v-loading="formLoading"
      :options="requestFormOptions"
      :getModelValue="getFormData"
    >
      <!-- <template #roleItems>角色权限进行插槽展示</template> -->
    </SmForm>

    <template #footer>
      <el-button @click="submitFormDB" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { addProperty } from "@/components/SmForm/src/utils";
import { createDBFn } from "@/utils/decorate";
import {
  getCustomerList,
  getOrganizationList,
  getVehicleBrandModelsList,
  getVehicleCategoryList,
  getVehicleNaturesList,
  getVehiclePlateTypesList,
} from "@/commonData";
import { createInputList } from "@/utils/form";
import VehicleAPI from "@/api/config/car-manage";
import { certTypeList, ethnicityList, genderList, isNotList } from "@/commonData/dict";
import { numToString } from "@/utils/transform";

/** 仓库 表单 */
defineOptions({ name: "OpenForm" });

const { t } = useI18n(); // 国际化

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(""); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(""); // 表单的类型：create - 新增；update - 修改
const initFormData = () => {
  return {};
};
const formData = ref(initFormData());
const formRef = ref(); // 表单 Ref

const customerList = ref([]);
const vehicleCategoryList = ref([]);
const vehicleNaturesList = ref([]);
const vehiclePlateTypesList = ref([]);
const vehicleBrandModelsList = ref([]);

const requestFormOptions: any = ref([]);

const createRequestFormOptions = () => {
  const list = createInputList([
    { prop: "approvedCapacity", label: "核定人数" },
    { prop: "approvedLoad", label: "核定载客/质量" },
    { prop: "avgMileage", label: "平均行驶里程 (公里)" },
    { prop: "claimCount", label: "历史出险次数" },
    { prop: "curbWeight", label: "整备质量(kg)" },

    {
      prop: "customerId",
      type: "select",
      data: customerList,
      label: "所属客户",
      attrs: { requiredFlag: true },
    },
    { prop: "displacement", label: "排量 (L)" },
    { prop: "engineNo", label: "发动机号码", attrs: { requiredFlag: true } },
    { type: "date-picker", prop: "firstRegDate", label: "初登日期" },
    {
      prop: "isImported",
      type: "select",
      data: isNotList,
      label: "是否进口价格",
    },
    { prop: "ownerAddress", label: "所在地址" },
    { type: "date-picker", prop: "ownerBirthday", label: "出生日期" },
    { type: "date-picker", prop: "ownerCertExpiryDate", label: "证件有效期截止日期" },

    { prop: "ownerCertNumber", label: "证件号码" },
    { type: "select", data: certTypeList, prop: "ownerCertType", label: "证件类型" },
    { type: "select", data: ethnicityList, prop: "ownerEthnicity", label: "民族" },
    { type: "select", data: genderList, prop: "ownerGender", label: "性别" },

    { prop: "ownerName", label: "车主姓名" }, //(被统筹人)
    { prop: "plateNo", label: "车牌号", attrs: { requiredFlag: true } },
    { prop: "power", label: "功率 (KW" },
    { prop: "purchasePrice", label: "车辆价格" },
    { prop: "ratedPayload", label: "额定载质量(kg)" },
    { prop: "totalWeight", label: "总质量(kg)" },

    // 估计要下拉了
    {
      type: "select",
      data: vehicleBrandModelsList,
      prop: "vehicleBrandModel",
      label: "厂牌型号",
      attrs: { requiredFlag: true },
    },
    { type: "select", data: vehicleCategoryList, prop: "vehicleCategoryId", label: "车辆种类" },
    { type: "select", data: vehicleNaturesList, prop: "vehicleNatureId", label: "车辆性质" },
    { type: "select", data: vehiclePlateTypesList, prop: "vehiclePlateTypeId", label: "号牌种类" },

    { prop: "vin", label: "车架号", attrs: { requiredFlag: true } },
  ]);

  addProperty(list);
  return list;
};

// const createRequestFormOptions = () => {
//   return mockForm(mockArr);
// };

requestFormOptions.value = createRequestFormOptions();

/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true;
  dialogTitle.value = t("action." + type);
  formType.value = type;
  resetForm();

  getCustomerList(customerList);
  getVehicleCategoryList(vehicleCategoryList);
  getVehicleNaturesList(vehicleNaturesList);
  getVehiclePlateTypesList(vehiclePlateTypesList);
  getVehicleBrandModelsList(vehicleBrandModelsList);

  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      formData.value = await VehicleAPI.getInfo(id);

      numToString(formData, [
        "purchasePrice",
        "ratedPayload",
        "totalWeight",
        "approvedLoad",
        "claimCount",
        "curbWeight",
        "approvedCapacity",
      ]);

      // 主动触发表单数据回显
      formRef.value.initForm();
    } finally {
      formLoading.value = false;
    }
  }
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(["success"]); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as any;
    if (formType.value === "create") {
      await VehicleAPI.create(data);
    } else if (formType.value === "update") {
      await VehicleAPI.update(data.id, data);
    }
    ElMessage.success("操作成功");
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit("success");
  } finally {
    formLoading.value = false;
  }
};
const submitFormDB = createDBFn(submitForm);

/** 重置表单 */
const resetForm = () => {
  formData.value = initFormData();
  formRef.value?.resetFields();
};

const getFormData = () => {
  return formData.value;
};
</script>
